<template>
  <Modal
    :mask-closable="false"
    v-model="showAdd"
    @on-visible-change="
      (e) => {
        !e && handdleCancel();
      }
    "
    :width="800"
    :title="isedit ? '新增内容' : '编辑内容'"
    :footer-hide="true"
    :draggable="true"
  >
    <Form ref="create" :model="contentInfo" :rules="rules" :label-width="70">
      <Row>
        <Col span="15">
          <FormItem label="项目" prop="project_id" required>
            <Select v-model="contentInfo.project_id" placeholder="项目">
              <Option
                v-for="item in condition.projectList"
                clearable
                :filterable="condition.projectList.length >= 10"
                @on-open-change="showAll"
                :value="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem label="类型" prop="type" required>
            <RadioGroup v-model="contentInfo.type" @on-change="changeType">
              <template v-for="item in condition.typeList" :key="item.value">
                <Radio :label="item.value"
                  ><span>{{ item.label }}</span></Radio
                >
              </template>
            </RadioGroup>
          </FormItem>

          <FormItem label="标题" prop="title" required>
            <Input
              v-model="contentInfo.title"
              placeholder="请输入标题（50字以内）"
              :maxlength="30"
            />
          </FormItem>

          <FormItem label="分类" prop="c_id" required>
            <Select
              v-model="contentInfo.c_id"
              clearable
              :filterable="condition.cList.length >= 10"
              @on-open-change="showAll"
              placeholder="请选择分类"
            >
              <Option
                v-for="item in condition.cList"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>

          <FormItem
            label="视频"
            prop="videofiles"
            v-if="contentInfo.type == 1"
            required
          >
            <Upload
              :action="fileUrl"
              :accept="supportVideo"
              :show-upload-list="false"
              :before-upload="videoBeforeUpload"
              :on-error="videoUploadError"
            >
              <Button type="primary" :loading="loadingUpload">上传</Button>
              <Tooltip
                :max-width="300"
                placement="top"
                :content="'支持视频格式：' + supportVideo"
                class="ivu-ml-8"
              >
                <Icon type="ios-alert-outline" size="20" color="#2db7f5" />
              </Tooltip>
            </Upload>
            <Progress
              v-if="progress && progress != 100"
              :percent="progress"
              :stroke-width="5"
            />
            <ul class="ivu-upload-list">
              <li
                class="ivu-upload-list-file ivu-upload-list-file-finish"
                style="display: inline-block"
                v-for="item in contentInfo.videofiles"
                :key="item.url"
              >
                <span><Icon type="ios-videocam" /> {{ item.file }}</span>
                <i
                  class="ivu-icon ivu-icon-ios-close ivu-upload-list-remove"
                  @click="removeVideo"
                ></i>
              </li>
            </ul>
          </FormItem>
          <FormItem
            label="封面图"
            prop="imgfiles"
            v-if="contentInfo.type == 2"
            required
          >
            <Upload
              :action="fileUrl"
              :accept="supportImg"
              multiple
              :show-upload-list="false"
              :before-upload="imgBeforeUpload"
              :on-error="imgUploadError"
            >
              <Button
                type="primary"
                :loading="loadingUpload"
                @click="showMaxSize = true"
                >上传</Button
              >
              <Tooltip
                :max-width="300"
                placement="top"
                :content="'支持图片格式：' + supportImg"
                class="ivu-ml-8"
              >
                <Icon type="ios-alert-outline" size="20" color="#2db7f5" />
              </Tooltip>
            </Upload>
            <div class="imgList ivu-mt-16">
              <div
                class="demo-upload-list"
                v-for="(item, index) in contentInfo.imgfiles"
                :key="item.url"
              >
                <img :src="item.url" fit="cover" width="40" height="40" />
                <div class="demo-upload-list-cover">
                  <Icon
                    type="ios-eye-outline"
                    @click="handleView(index)"
                  ></Icon>
                  <Icon
                    type="ios-trash-outline"
                    @click="handleRemove(item)"
                  ></Icon>
                </div>
              </div>
            </div>
          </FormItem>
        </Col>
        <Col span="1" class="ivu-text-center">
          <Divider type="vertical" style="height: 100%" />
        </Col>
        <Col span="8">
          <FormItem label="关键词" prop="keyword">
            <Input v-model="contentInfo.keyword" placeholder="关键词按,分隔" />
          </FormItem>
          <FormItem label="标签" prop="tags">
            <Select
              placeholder="请选择标签"
              multiple
              filterable
              allow-create
              @on-open-change="openChange"
              ref="tags"
              v-model="contentInfo.tags"
            >
              <Option
                v-for="item in this.condition.tagList"
                :value="isNaN(item.value) ? item.value : parseInt(item.value)"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem label="医生" prop="doctor_id">
            <Select
              placeholder="请选择医生"
              :filterable="condition.doctorList.length >= 10"
              @on-open-change="showAll"
              v-model="contentInfo.doctor_id"
              clearable
            >
              <Option
                v-for="item in this.condition.doctorList"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem label="投流" prop="is_stream" required>
            <RadioGroup v-model="contentInfo.is_stream">
              <Radio :label="1"><span>是</span></Radio>
              <Radio :label="0"><span>否</span></Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="状态" prop="publish_status" required>
            <Select v-model="contentInfo.publish_status">
              <Option
                v-for="item in condition.statusList"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
        </Col>
        <Col class="ivu-mt-16" span="24">
          <div class="ivu-mb-16">
            <ckeditor
              :editor="editor"
              v-model="contentInfo.content"
              :config="editorConfig"
              style="height: 300px"
            ></ckeditor>
          </div>
        </Col>
      </Row>
    </Form>
    <div slot="footer" style="text-align: right">
      <Button type="default" @click="handdleCancel">取消</Button>
      <Button
        type="primary"
        @click="ok"
        :loading="btnLoading"
        style="margin-left: 10px"
        >确定</Button
      >
    </div>
  </Modal>
</template>
<script>
import Setting from "@/setting";
import util from "@/libs/util";
import ClassicEditor from "@ckeditor/ckeditor5-build-classic";
import CKEditor from "@ckeditor/ckeditor5-vue";
import {
  createContent,
  contentInfo,
  updateContent,
  uploadFile,
} from "@api/content.js";
import { checkTgaStatus } from "@api/toolnavigation.js";
export default {
  components: { ckeditor: CKEditor.component },
  name: "add",
  props: ["showAdd", "isedit", "id"],
  data() {
    return {
      btnLoading: false,
      condition: {
        projectList: [],
        tagList: [],
        typeList: [],
        cList: [],
        statusList: [],
        doctorList: [],
      },
      initTagList: [],
      fileUrl: "",
      loadingUpload: false,
      filesNum: [],
      maxFiles: 30,
      contentInfo: {
        project_id: "",
        type: 1,
        title: "",
        content: "",
        keyword: "",
        c_id: "",
        is_stream: 0,
        publish_status: 1,
        tags: [],
        attachment: [],
        videofiles: [],
        imgfiles: [],
        doctor_id: "",
      },
      supportImg: "",
      supportVideo: "",
      editor: ClassicEditor,
      editorConfig: {
        language: "zh-cn",
        toolbar: {
          items: [
            "undo",
            "|",
            "heading",
            "|",
            "bold",
            "italic",
            "|",
            "link",
            "blockQuote",
            "|",
            "bulletedList",
            "numberedList",
            "outdent",
            "indent",
          ],
          shouldNotGroupWhenFull: false,
        },
      },
      rules: {
        project_id: [{ required: true, message: "请选择项目" }],
        type: [{ required: true, message: "请选择类型" }],
        title: [
          {
            required: true,
            pattern: /^.{1,50}$/,
            message: "请输入标题（50字以内）",
          },
        ],
        c_id: [{ required: true, message: "请选择分类" }],
        is_stream: [{ required: true, message: "请选择是否投流" }],
        publish_status: [{ required: true, message: "请选择状态" }],
        videofiles: [{ required: true, message: "请上传视频" }],
        imgfiles: [{ required: true, message: "请上传图片" }],
      },
      controller: null,
      showMaxSize: false,
      progress: 0,
    };
  },
  watch: {
    "contentInfo.content"(newVal, oldVal) {
      this.contentInfo.content = newVal.replaceAll(
        /<img [^>]*src=['"]([^'"]+)[^>]*>/gi,
        ""
      );
    },
    showAdd() {
      if (this.showAdd) {
        this.btnLoading = false;
        this.loadingUpload = false;
        this.filesNum = [];
        this.getInfo();
        this.fileUrl =
          Setting.request.apiBaseURL +
          `/common/file/upload?auth_access_token=${util.cookies.get("token")}`;
      }
    },
    "contentInfo.tags"(newData, oldData) {
      if (newData.length > oldData.length) {
        let flag = false;
        let hasTags = false;
        this.condition.tagList.forEach((item) => {
          if (
            newData[newData.length - 1] == item.value ||
            newData[newData.length - 1] == item.label
          ) {
            flag = true;
            this.contentInfo.tags[this.contentInfo.tags.length - 1] = isNaN(
              item.value
            )
              ? item.value
              : parseInt(item.value);
            this.contentInfo.tags = [...new Set(this.contentInfo.tags)];
            return;
          }
        });
        if (!flag) {
          checkTgaStatus({ name: newData[newData.length - 1], type: 1 }).then(
            (res) => {
              if (res.res) {
                this.condition.tagList.push({
                  value: isNaN(newData[newData.length - 1])
                    ? newData[newData.length - 1]
                    : parseInt(newData[newData.length - 1]),
                  label: newData[newData.length - 1],
                });
                this.contentInfo.tags[this.contentInfo.tags.length - 1] = isNaN(
                  newData[newData.length - 1]
                )
                  ? newData[newData.length - 1]
                  : parseInt(newData[newData.length - 1]);
                hasTags = true;
                return;
              }
              if (!hasTags) {
                let tagIds = JSON.parse(JSON.stringify(this.contentInfo.tags));
                tagIds.pop();
                this.contentInfo.tags = tagIds;
                this.$Message.success("此标签已被禁用！");
              }
            }
          );
        }
      }
    },
  },
  methods: {
    showAll(e) {
      if (e) {
        let downList = document.querySelectorAll(
          ".ivu-select-dropdown-list .ivu-select-item"
        );
        downList.forEach((item) => {
          item.style.display = "block";
        });
      }
    },
    handdleCancel() {
      if (this.controller) {
        this.progress = 0;
        this.controller.abort();
      }
      this.$emit("closeAddModal", false);
    },
    changeType() {
      this.loadingUpload = false;
      if (this.controller) {
        this.progress = 0;
        this.controller.abort();
      }
    },

    videoBeforeUpload(e) {
      if (e.size > 2 * 1024 * 1024 * 1024) {
        this.$Message.error("文件大小不能超过2G");
        return false;
      }
      this.loadingUpload = true;
      this.controller = new AbortController();
      this.progress = 0;
      uploadFile({ site: "content", module: "index", file: e }, this)
        .then((res) => {
          this.contentInfo.videofiles = [res];
          this.loadingUpload = false;
        })
        .catch((res) => {
          this.loadingUpload = false;
        });
      return false;
    },
    videoUploadError(error, file, fileList) {
      this.$Message.error(error);
      this.loadingUpload = false;
    },
    imgBeforeUpload(e) {
      if (this.filesNum.length >= this.maxFiles) {
        if (this.showMaxSize) {
          this.$Message.success("图片数量不能超过" + this.maxFiles + "张！");
          this.showMaxSize = false;
        }
        return false;
      }
      if (e.size > 1024 * 1024 * 20) {
        this.$Message.error("文件大小不能超过20M");
        return false;
      }
      this.loadingUpload = true;
      this.filesNum.push(e);
      this.controller = new AbortController();
      uploadFile({ site: "content", module: "index", file: e }, this)
        .then((res) => {
          this.contentInfo.imgfiles.push(res);
          this.loadingUpload = false;
        })
        .catch((res) => {
          this.loadingUpload = false;
        });
      return false;
    },
    imgUploadError(error, file, fileList) {
      this.$Message.error(error);
      this.loadingUpload = false;
    },
    handleView(index) {
      let imgArr = [];
      this.contentInfo.imgfiles.forEach((item) => {
        imgArr.push(item.url);
      });
      this.$hevueImgPreview({
        multiple: true,
        nowImgIndex: index,
        imgList: imgArr,
      });
    },
    handleRemove(file) {
      const fileList = this.contentInfo.imgfiles;
      this.contentInfo.imgfiles.splice(fileList.indexOf(file.file), 1);
      this.filesNum.splice(fileList.indexOf(file.file), 1);
    },
    removeVideo() {
      this.contentInfo.videofiles = [];
    },
    getInfo() {
      let params = {};
      if (!this.isedit) {
        params.id = this.id;
      }
      contentInfo(params).then((res) => {
        this.supportImg = res.support_img.join(" , ");
        this.supportVideo = res.support_video.join(" , ");
        this.condition.projectList = res.condition.project;
        this.condition.tagList = [...res.condition.tag];
        this.initTagList = [...res.condition.tag];
        this.condition.typeList = res.condition.type;
        this.condition.cList = res.condition.classify;
        this.condition.statusList = res.condition.publist_status;
        this.condition.doctorList = res.condition.doctor;
        this.contentInfo = {
          project_id: "",
          type: 1,
          title: "",
          content: "",
          keyword: "",
          c_id: "",
          doctor_id: "",
          is_stream: 0,
          publish_status: 1,
          tags: [],
          attachment: [],
          videofiles: [],
          imgfiles: [],
        };
        this.$refs.create.resetFields();
        if (!this.isedit) {
          this.contentInfo = {
            id: res.id,
            project_id: res.project_id,
            type: res.type,
            title: res.title,
            content: res.content,
            keyword: res.keyword.join(","),
            c_id: res.c_id,
            doctor_id: res.doctor_id,
            is_stream: res.is_stream,
            publish_status: res.publish_status,
            tags: res.tag_ids,
            videofiles: [],
            imgfiles: [],
          };
          res.attachment.forEach((item) => {
            this.filesNum.push({
              name: item.file,
              url: item.file_url,
            });
            if (this.contentInfo.type == "1") {
              this.contentInfo.videofiles.push({
                file: item.file,
                url: item.file_url,
              });
            }
            if (this.contentInfo.type == "2") {
              this.contentInfo.imgfiles.push({
                file: item.file,
                url: item.file_url,
              });
            }
          });
        }
      });
    },
    addContent() {
      if (this.loadingUpload) {
        this.$Message.success("文件还在上传中请等待一会~");
        return;
      }
      this.btnLoading = true;
      let tagarr = [];
      this.contentInfo.tags.forEach((item) => {
        let hasTag = false;
        this.initTagList.forEach((el) => {
          if (item == el.value) {
            tagarr.push(el);
            hasTag = true;
            return;
          }
        });
        if (!hasTag) {
          tagarr.push({ value: 0, label: item });
        }
      });

      let attachment = [];
      if (this.contentInfo.type == "1") {
        this.contentInfo.videofiles.forEach((item) => {
          attachment.push(item.file);
        });
      } else if (this.contentInfo.type == "2") {
        this.contentInfo.imgfiles.forEach((item) => {
          attachment.push(item.file);
        });
      }
      const params = {
        project_id: this.contentInfo.project_id,
        type: this.contentInfo.type,
        title: this.contentInfo.title,
        content: this.contentInfo.content,
        keyword: this.contentInfo.keyword.trim()
          ? this.contentInfo.keyword
              .replaceAll(" ", "")
              .replaceAll("，", ",")
              .split(",")
          : [],
        c_id: this.contentInfo.c_id,
        doctor_id: this.contentInfo.doctor_id,
        is_stream: this.contentInfo.is_stream,
        publish_status: this.contentInfo.publish_status,
        tags: tagarr,
        attachment: attachment,
      };
      if (this.isedit) {
        createContent(params)
          .then((res) => {
            this.$Message.success("添加成功");
            this.btnLoading = false;
            this.$emit("closeAddModal", false, "add");
          })
          .catch(() => {
            this.btnLoading = false;
          });
      } else {
        updateContent(Object.assign({}, params, { id: this.contentInfo.id }))
          .then((res) => {
            this.$Message.success("编辑成功");
            this.btnLoading = false;
            this.$emit("closeAddModal", false, "edit");
          })
          .catch(() => {
            this.btnLoading = false;
          });
      }
    },
    ok() {
      this.$refs.create.validate((valid) => {
        if (valid) {
          this.addContent();
        } else {
          this.addModal = true;
          return;
        }
      });
    },
    openChange(e) {
      if (!e) {
        this.$refs.tags.query = "";
      }
    },
  },
};
</script>
<style lang="less">
.ck-editor__editable {
  width: 100%;
  height: 220px;
}
</style>
<style lang="less" scoped>
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.imgList {
  width: 100%;
  white-space: nowrap;
  overflow: auto;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>
